<template>
	<view class="pay-confirm">
		<base-navbar back-color="#fff" title="收银台" :is-back="false"></base-navbar>
		<view class="total" style="text-align: center;padding: 30rpx;">
			<text class="label">需要支付</text>
			<view class="" style="padding-top: 20rpx;">
				￥<text style="font-size: 40rpx;font-weight: bold;">{{orderInfo.pay_amount}}</text>
			</view>
		</view>
		<uni-group class="pay-way" title="支付方式">
			<view v-if="parseFloat(memberInfo.balance_fee)>0">
				<view class="card" style="padding: 10px 0px;">
					<view class="item" style="width: 10%;">
						<uni-icons type="auth-filled" :color="themeColor.theme" size="22"></uni-icons>
					</view>
					<view class="item" style="width: 80%;">
						<view class="">
							账户余额
						</view>
						<view class="" style="font-size: 22rpx;color: #787878;">
							￥{{memberInfo.balance_fee}}
						</view>
					</view>
					<view class="item">
						<checkbox value="cb" :checked="yeChecked" @click="choosePay(0)" style="transform:scale(0.7)" />
					</view>
				</view>
				<hr color="#d0d0d0" size="1" />
			</view>
			<view v-if="orderInfo.pay_amount > 0">
				<view v-if="!environment.isAlipay || payWx">
					<view class="card" style="padding: 10px 0px;">
						<view class="item" style="width: 10%;">
							<uni-icons type="weixin" :color="themeColor.theme" size="24"></uni-icons>
						</view>
						<view class="item" style="width: 80%;">
							<view class="">
								微信支付
							</view>
							<view class="" style="font-size: 22rpx;color: #787878;">
								推荐使用微信支付
							</view>
						</view>
						<view class="item">
							<checkbox value="cb" :checked="wxChecked" @click="choosePay(1)"
								style="transform:scale(0.7)" />
						</view>
					</view>
					<hr color="#d0d0d0" size="1" />
				</view>
				<view v-if="!environment.isWeChat || payZfb">
					<view class="card" style="padding: 10px 0px;">
						<view class="item" style="width: 10%;">
							<uni-icons type="icon-iconfonticons" custom-prefix="iconfont" :color="themeColor.theme"
								size="24"></uni-icons>
						</view>
						<view class="item" style="width: 80%;">
							<view class="">
								支付宝支付
							</view>
							<view class="" style="font-size: 22rpx;color: #787878;"></view>
						</view>
						<view class="item">
							<checkbox value="cb" :checked="zfbChecked" @click="choosePay(2)"
								style="transform:scale(0.7)" />
						</view>
					</view>
				</view>
			</view>
			<view class="">
				<button type="primary" :style="{'background-color': themeColor.theme}" @click="pay()">确认支付</button>
			</view>
		</uni-group>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import checkLogin from '@/utils/login';
	import {
		ref,
		reactive,
		toRefs,
		inject
	} from 'vue';
	import {
		onLoad,
		onShow,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';
	// #ifdef H5
	// import jweixin from "jweixin-module";
	// #endif

	const state = reactive({
		themeColor: JSON.parse(cache.get('themeColor')),
		environment: {
			isWeChat: true,
			isAlipay: false,
			isBrowser: false,
		},
		trade_no: "",
		orderInfo: [],
		memberInfo: [],
		yeChecked: false,
		wxChecked: true,
		zfbChecked: false,
		pay_type: 1,
		payWx: true,
		payZfb: false,

	});

	onLoad((opt) => {
		// #ifdef H5
		state.environment = checkEnvironment();
		console.log('H5浏览器类型', state.environment)
		// #endif
		// #ifdef MP-WEIXIN
		state.payWx = true;
		// #endif
		// #ifdef MP-ALIPAY
		state.payZfb = true;
		// #endif
		// #ifdef APP
		state.payWx = true;
		state.payZfb = true;
		// #endif

		state.trade_no = opt.trade_no;
		//登录过期自动登录
		if (!checkLogin()) {
			pageRoute('/pages/users/login/login');
		} else {
			getOrderInfo();
			getMemberWallet();
		}
	});

	onShow(() => {});

	onPullDownRefresh((e) => {
		console.log("下拉刷新", e);
	});

	onReachBottom((e) => {
		console.log("上拉加载更多", e);
	});

	function getOrderInfo() {
		request.get("order/getOrderInfo", {
			trade_no: state.trade_no
		}).then(res => {
			console.log('订单', res);
			state.orderInfo = res.data;
		})
	}

	function getMemberWallet() {
		request.get("member/getMemberWallet").then(res => {
			console.log('会员钱包', res);
			state.memberInfo = res.data;
		})
	}

	function choosePay(item) {
		state.pay_type = item
		if (item == 0) {
			//余额支付
			state.yeChecked = true;
			state.wxChecked = false;
			state.zfbChecked = false;
		} else if (item == 1) {
			//微信支付
			state.yeChecked = false;
			state.wxChecked = true;
			state.zfbChecked = false;
		} else {
			//支付宝支付
			state.yeChecked = false;
			state.wxChecked = false;
			state.zfbChecked = true;
		}
	}

	function pay() {
		if (state.pay_type == 0) { //余额支付
			if (parseFloat(state.memberInfo.balance_fee) < parseFloat(state.orderInfo.pay_amount)) {
				uni.showToast({
					title: "余额不足",
					icon: 'error'
				});
				return;
			}
			request.post('payment/paymentBalance', {
				trade_no: state.trade_no
			}).then(resp => {
				console.log('余额支付-1', resp)
				if (resp.code === 1) {
					paySuccess(state.pay_type)
				} else {
					uni.showToast({
						title: resp.msg,
						icon: 'success'
					});
				}
			})
		} else if (state.pay_type == 1) { //微信支付
			request.post("payment/wxpay", {
				trade_no: state.trade_no,
				pay_type: state.pay_type,
			}).then(res => {
				console.log('微信支付-1', res);
				if (res.code === 1) {
					// #ifdef H5
					let jsApiParameters = {
						appId: res.data.appId, //公众号ID，由商户传入
						nonceStr: res.data.nonceStr, //随机串
						timeStamp: res.data.timeStamp, //时间戳，自1970年以来的秒数
						package: res.data.package,
						paySign: res.data.paySign, //微信签名
						signType: res.data.signType, //微信签名方式
					};
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest', jsApiParameters,
						function(res) {
							console.log(res);
							if (res.err_msg == "get_brand_wcpay_request:ok") {
								paySuccess(state.pay_type);
							} else {
								if (res.err_msg == 'get_brand_wcpay_request:cancel') {
									uni.showModal({
										content: "交易取消，订单已取消",
										showCancel: false
									})
								} else {
									uni.showModal({
										content: "支付失败,原因为: " + res.err_msg + "，订单已取消",
										showCancel: false
									})
								}
								//取消支付
								cancelPay();
							}
						}
					);
					// #endif

					// #ifdef MP-WEIXIN
					uni.requestPayment({
						appId: res.data.appId, //小程序ID，由商户传入
						nonceStr: res.data.nonceStr, //随机串
						timeStamp: res.data.timeStamp, //时间戳，自1970年以来的秒数
						package: res.data.package,
						paySign: res.data.paySign, //微信签名
						signType: res.data.signType, //微信签名方式
						success(resp) {
							if (resp.errMsg == "requestPayment:ok") {
								paySuccess(state.pay_type);
							}
						},
						fail(e) {
							if (e.errMsg == "requestPayment:fail cancel") {
								uni.showToast({
									title: "支付已取消！",
									icon: 'error'
								});
							} else {
								console.log(e.errMsg)
								uni.showToast({
									title: "错误：" + e.errMsg,
									icon: 'error'
								});
							}
							//取消支付
							cancelPay();
						}
					})
					// #endif
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'error'
					});
				}
			})
		} else { //支付宝支付
			console.log('支付宝支付');
			/* request.post("/payment/payment", {
				trade_no: state.trade_no,
				pay_type: state.pay_type,
			}).then(res => {
				console.log('支付宝支付-1', res);
			}); */
		}
	}

	//支付成功
	function paySuccess(pay_type) {
		//更新订单状态（回调）
		request.post('payment/paySuccess', {
			trade_no: state.trade_no,
			pay_type: pay_type
		}).then(res => {
			// if (res.code === 1) {
			uni.showToast({
				title: "支付成功",
				icon: 'success'
			});
			setTimeout(() => {
				uni.navigateTo({
					url: "/pages/tabbar/order/order"
				})
			}, 1000)
			/* } else {
				uni.showToast({
					title: res.msg,
					icon: 'error'
				});
			} */
		})
	}

	function cancelPay() {
		console.log('取消支付');
		//修改订单状态
		/* request.post('order/changeOrderStatus', {
			trade_no: state.trade_no,
			order_status: 0, //订单状态：0->待付款；1->待确认；2->待发货；3->待发货；4->待评价；5->已完成；6->已关闭；7->无效订单；8->申请退款；9->退款成功
		}).then(res => {
			console.log('修改订单状态', res)
		}) */
	}

	//判断打开浏览器
	function checkEnvironment() {
		let userAgent = navigator.userAgent.toLowerCase();
		//判断是否是微信浏览器
		let isWeChat = userAgent.indexOf('micromessenger') !== -1;
		//判断是否是支付宝浏览器
		let isAlipay = userAgent.indexOf('alipayclient') !== -1;
		//判断是否是普通浏览器
		let isBrowser = !isWeChat && !isAlipay;

		return {
			isWeChat: isWeChat,
			isAlipay: isAlipay,
			isBrowser: isBrowser
		};
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	};

	function pageTabRoute(url) {
		uni.switchTab({
			url
		});
	};

	const {
		themeColor,
		environment,
		trade_no,
		orderInfo,
		memberInfo,
		yeChecked,
		wxChecked,
		zfbChecked,
		pay_type,
		payWx,
		payZfb,
	} = toRefs(state);
</script>

<style lang="scss">
	page {
		background-color: $bg-color;
	}

	.item {
		float: left;
	}

	.pay-confirm {
		padding: $margin-24 $margin-24 calc(env(safe-area-inset-bottom) + 100rpx);

		.card {
			// margin-bottom: $margin-24;
			background-color: $bg-inverse-color;
			border-radius: $radius-12;
			height: 80rpx
		}

		.address-card {
			@include f-between;
			padding: $margin-24;

			.icon-map {
				@include f-center;
				width: 36rpx;
				height: 36rpx;
				// background-color: $theme-color;
				border-radius: $radius-circle;
			}

			.info {
				flex: 1;
				margin-left: $margin-16;

				.name {
					color: $main-color;
					font-weight: bold;
				}

				.desc,
				.phone {
					font-size: $font-24;
					color: $tips-color;
				}

				.phone {
					margin-left: $margin-12;
				}

				.desc {
					margin-top: $margin-8;
				}
			}
		}
	}
</style>